package bo;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.ServletUtils;

/**
 * Servlet implementation class Daorudaochu
 */
@WebServlet("/daorudaochu")
public class Daorudaochu extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Daorudaochu() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action = request.getParameter("action");
		HttpSession session = request.getSession();
		List<book> list = (List<book>) session.getAttribute("list");
		book exceldao = new book();
		String saveDirectory = this.getServletContext().getRealPath("/file");
		if("daoru".equals(action)) {
			int maxPostSize = 5 * 1024 * 1024;
			MultipartRequest multi = new MultipartRequest(request,saveDirectory,maxPostSize,"utf-8");
			
			File excelFile = multi.getFile("file1");
			if(excelFile != null) {
				try {
					exceldao.ImportData(excelFile);
					excelFile.delete();
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
			response.sendRedirect("showsuccess.jsp");
		}else if("daochu".equals(action)) {
			String fileName = "student.xls";
			try {
				exceldao.ExportExcel(new File(saveDirectory+"/"+fileName),list);
				String isofilename = new String(fileName.getBytes("gbk"),"iso-8859-1");
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposion", "attachment;filename="+isofilename);
				ServletOutputStream out = null;
				out = response.getOutputStream();
				ServletUtils.returnFile(saveDirectory+"/"+fileName,out);
				new File(saveDirectory+"/"+fileName).delete();
			}catch(Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
